<?php
/**
 * 节目单文件生成（江苏华博大电视使用)
 * @author:xinxin.deng
 * @date: 2017/9/20 14:23
 */
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 1);
set_time_limit(0);
include_once dirname(dirname(__FILE__)) . '/mgtv_v2/mgtv_init.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/nn_const.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/common.php';
include_once dirname(dirname(__FILE__)) . '/nn_logic/nl_common.func.php';

class timer_execute extends nn_timer
{
    public $str_date = null;
    public $str_date_time = null;
    public $arr_full_assets_site = array();
    
    public $str_base_dir=null;
    /**
     * 定时器初始化
     * @see nn_timer::action()
     */
    public function action($params = null)
    {
        $this->msg('开始执行...');
        $this->init($params);
        $this->msg('执行结束...');
    }
    
    /**
     * 初始化
     */
    public function init($params=null)
    {
        include_once dirname(dirname(__FILE__)) . '/nn_cms_config/nn_cms_global.php';
        include_once dirname(dirname(__FILE__)) . '/nn_logic/bigtv_bind/bigtv_bind.class.php';
        include_once dirname(dirname(__FILE__)) . '/nn_logic/playbill/playbill_item.class.php';
        $str_third_playbill_pool = $params["bk_queue_value"];
        if(strlen($str_third_playbill_pool) <1 || $str_third_playbill_pool != 'placeholder')
        {
            $this->msg("[redis节目单池中返回数据为空]".$str_third_playbill_pool);
            return ;
        }
        $max_day = (int)$this->arr_params['bk_queue_config']['nns_ext_info']['max_day'] > 0 ? (int)$this->arr_params['bk_queue_config']['nns_ext_info']['max_day'] : 7;
        $result_bigtv_bind = nl_bigtv_bind::query_all($this->obj_dc);
        if($result_bigtv_bind['ret'] !=0)
        {
            $this->msg(var_export($result_bigtv_bind,true));
            return ;
        }
        if(!isset($result_bigtv_bind['data_info']) || !is_array($result_bigtv_bind['data_info']) || empty($result_bigtv_bind['data_info']))
        {
            $this->msg('sql查询到任何绑定的大电视数据：'.var_export($result_bigtv_bind,true));
            return ;
        }
        $date = date('Y-m-d', strtotime("-{$max_day} days"));
        $this->make_dir();
        foreach ($result_bigtv_bind['data_info'] as $bigtv_bind)
        {
            if(strlen($bigtv_bind['nns_bk_channel_id']) <1)
            {
                $this->msg('nns_bk_channel_id 为空：'.$bigtv_bind['nns_bk_channel_id']);
            }
            $result_playbill = nl_playbill_item::query_by_liveid_and_time($this->obj_dc, $bigtv_bind['nns_bk_channel_id'],$date);
            if($result_playbill['ret'] !=0)
            {
                $this->msg(var_export($result_playbill,true));
                return ;
            }
            if(!isset($result_playbill['data_info']) || !is_array($result_playbill['data_info']) || empty($result_playbill['data_info']))
            {
                $this->msg("sql查询频道[{$bigtv_bind['nns_bk_channel_id']}];日期[{$date}] 数据为空");
                continue ;
            }
            $xml = $this->make_xml_file($bigtv_bind['nns_bigtv_channel_name'], $result_playbill['data_info']);
            if ($xml == null)
            {
                $this->msg('生成xml失败，数据为：' . var_export($result_playbill['data_info'], true));
                continue;
            }
            $txt = $this->make_txt_file($bigtv_bind['nns_bigtv_channel_name'], $result_playbill['data_info']);
            if ($txt == null)
            {
                $this->msg('生成txt失败，数据为：' . var_export($result_playbill['data_info'], true));
                continue;
            }
            $this->make_file($bigtv_bind['nns_bigtv_channel_name'], $xml, 'xml');
            $this->make_file($bigtv_bind['nns_bigtv_channel_name'], $txt, 'txt');
        }
    }

    /**
     * @description:创建目录
     * @date: 2017/9/30 17:33
     */
    public function make_dir()
    {
        global $g_project_name;
        $project_name = $g_project_name;
        unset($g_project_name);
        $project_name = strlen($project_name) <1 ? $project_name : 'base';
        $base_dir = dirname(dirname(__FILE__)).'/data/third_part/'.$project_name.'/'.date("Ymd").'/'.date("His");
        $base_dir_txt = $base_dir.'/txt';
        $base_dir_xml = $base_dir.'/xml';
        if (!is_dir($base_dir_txt))
        {
            mkdir($base_dir_txt, 0777, true);
        }
        if (!is_dir($base_dir_xml))
        {
            mkdir($base_dir_xml, 0777, true);
        }
        $this->str_base_dir = $base_dir;
    }

    /**
     * @description:封装成txt
     * @date: 2017/9/30 17:33
     * @param $file_name
     * @param $arr_playbill
     * @return null|string
     */
    public function make_txt_file($file_name,$arr_playbill)
    {
        if (!isset($arr_playbill) || empty($arr_playbill) || !is_array($arr_playbill))
        {
            return null;
        }
        $create_time = date("YmdHis");
        $text = '';
        $text .= iconv('UTF-8', 'GB2312','频道名称') . ' ' . iconv('UTF-8', 'GB2312',$file_name) . ''."\n";
        $temp_bk_date='';
        foreach ($arr_playbill as $key => $val)
        {
            $begin_time = date('Y/m/d', strtotime($val['nns_begin_time']));

            if($temp_bk_date != $val['bk_date'] && $key!=0)
            {
                $text .= iconv('UTF-8', 'GB2312','节目长度') . '  1:41'."\n";
                $text .= "\n";
            }
            if($temp_bk_date != $val['bk_date'])
            {
                $text .= iconv('UTF-8', 'GB2312','播出日期') . '  ' . $begin_time . ''."\n";
                $text .= "\n";
            }
            $item_begin_time = date('H:i', strtotime($val['nns_begin_time']));
            $text .= $item_begin_time . '  ' . iconv('UTF-8', 'GB2312',$val['nns_name'])."\n";
            $temp_bk_date = $val['bk_date'];
        }
        $text .= iconv('UTF-8', 'GB2312','节目长度') . '  1:41'."\n";
        return $text;
    }

    /**
     * @description:组装xml
     * @date: 2017/9/30 17:44
     * @param $file_name
     * @param $arr_playbill
     * @return null|string
     */
    public function make_xml_file($file_name,$arr_playbill)
    {
        if (!isset($arr_playbill) || empty($arr_playbill) || !is_array($arr_playbill))
        {
            return null;
        }
        $create_time = date("YmdHis");
        $xml ='<?xml version="1.0" encoding="GB2312"?>'."\n";
        $xml.=  '<BroadcastData code="100000P00" creationtime="' . $create_time . '" version="2.0">'."\n";
        $xml.=      '<ProviderInfo id="TVIBE" name="TVIBE"/>'."\n";
        $xml.=      '<SchedulerData  type="PROGRAM">'."\n";
        $xml.=          '<Channel>'."\n";
        $xml.=              '<ChannelText language="chi">'."\n";
        $xml.=                      '<ChannelName>'. iconv('UTF-8', 'GB2312',$file_name) . '</ChannelName>'."\n";
        $xml.=              '</ChannelText>'."\n";
        //循环遍历频道下的节目单
        $temp_bk_date='';
        foreach ($arr_playbill as $key=>$item)
        {
            if($temp_bk_date != $item['bk_date'])
            {
                $num = 0;
            }
            $begin_time = date('YmdHis', strtotime($item['nns_begin_time']));
            $view_len = $this->sec_to_time($item['nns_time_len']);
            $xml.=          '<Event begintime="'. $begin_time .'" duration="' . $view_len . '" eventid="' . $num . '" eventtype="00">'."\n";
            $xml.=                  '<EventText language="chi">'."\n";
            $xml.=                      '<Name>' . iconv(mb_detect_encoding($item['nns_name']), 'GB2312',$item['nns_name']) . '</Name>'."\n";
            $xml.=                      '<ShortDescription/>'."\n";
            $xml.=                  '</EventText>'."\n";
            $xml.=          '</Event>'."\n";
            $num++;
            $temp_bk_date = $item['bk_date'];
        }
        $xml.=          '</Channel>'."\n";
        $xml.=      '</SchedulerData>'."\n";
        $xml.=  '</BroadcastData>'."\n";
        return $xml;
        
    }
    
    public function sec_to_time($times)
    {
        $result = '000000';
        if ($times>0) 
        {
            $hour = floor($times/3600);
            if(strlen($hour) <2)
            {
                $hour='0'.$hour;
            }
            $minute = floor(($times-3600 * $hour)/60);
            if(strlen($minute) <2)
            {
                $minute='0'.$minute;
            }
            $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
            if(strlen($second) <2)
            {
                $second='0'.$second;
            }
            $result = $hour.$minute.$second;
        }
        return $result;
    }
    
    
    public function make_file($file_name,$coontent,$type)
    {
        $base_file_name = $this->str_base_dir.'/'.$type.'/'.$file_name.'.'.$type;
        return @error_log($coontent, 3, $base_file_name);
    }
}
$arr_files = pathinfo(__FILE__);
$file_name = $arr_files['filename'];
$timer_execute = new timer_execute($file_name, $file_name,__FILE__,'playbill_to_localfile');
$timer_execute->run();
